<template>
  <div class="cart">
    <!-- 购物车为空的时候的数据展示 -->
    <div v-if="!cartList.length">
      <van-empty image="/images/cart/empty.jpg" image-size="300px" />
      <div @click="toHome" class="tip">购物车空空如也,快去添加商品吧</div>
    </div>

    <!-- 购物车不为空的数据展示 -->
    <div v-else>
      <!-- 商品部分 -->
      <div class="outbox">
        <div class="card" v-for="item in cartList" :key="item.id">
          <van-checkbox v-model="item.isChecked" @change="changeStatus(item)"></van-checkbox>
          <van-swipe-cell>
            <van-card
              :price="item.cartPrice"
              desc="手机"
              :title="item.skuName"
              :thumb="item.imgUrl"
            >
              <template #footer class="step">
                <div class="circular isshownum" v-if="isShowNum === 0" @click="changeInput">
                  x{{ item.skuNum }}
                </div>
                <van-stepper
                  v-else
                  class="circular"
                  theme="round"
                  button-size="22"
                  v-model="item.skuNum"
                  min="1"
                  max="200"
                  @change="changeNum($event, item)"
                />
              </template>
            </van-card>
            <template #right>
              <van-button
                square
                text="删除"
                type="danger"
                class="delete-button"
                @click="deleteOne(item.skuId)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </div>

      <!-- 底部导航栏 -->
      <van-submit-bar :price="allPrice" button-text="提交订单" @submit="onSubmit">
        <van-checkbox v-model="allChecked" @click="changeAllStatus(newStatus)">全选</van-checkbox>
        <template #tip>
          你的收货地址不支持配送, <span @click="onClickLink">修改地址</span>
        </template>
      </van-submit-bar>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  reqCartList,
  reqChangeGoodSingle,
  reqChangeGoodsAll,
  reqDeleteSingle,
  reqaddCart
} from '@/api/cart'
import router from '@/router'
import { IResCartItem } from '@/types/cart'
import { computed, onMounted, ref } from 'vue'
import { debounce } from 'lodash'

// 数据
const cartList = ref<IResCartItem[]>([])

const isShowNum = ref(0)

// 全选的新状态
const newStatus = ref()

// #region 所有方法
const onSubmit = async() => {
    router.push('/order')
}

const onClickLink = () => {}

// 数据发生变化
const changeNum = debounce(async (newVal: number, item: IResCartItem) => {
  console.log(newVal, item.oldVal)
  let gap = newVal - item.oldVal!
  console.log(gap)
  // 调用接口
  const res = await reqaddCart(item.skuId, gap)
  if (res.code === 200) {
    // 修改旧值
    item.oldVal = newVal
  }
}, 1000)

// 更改购物车单个状态
const changeStatus = (goodSingle: IResCartItem) => {
  // console.log(e,goodSingle);
  const isChecked = goodSingle.isChecked ? 1 : 0
  const skuId = goodSingle.skuId
  // 调用接口更改商品的选中状态
  reqChangeGoodSingle(skuId, isChecked)
}

// 更改购物车的全选数据
const changeAllStatus = async (newStatus: number) => {
  console.log(newStatus)

  // 准备skuIdlist数组
  const skuIdList = <any>[]

  cartList.value.forEach((item) => {
    skuIdList.push(item.id)
  })

  // 传递参数，发送请求
  const res = await reqChangeGoodsAll(skuIdList, newStatus)

  if (res.code === 200) {
    // 请求成功 更新本地数据
    cartList.value.forEach((item) => {
      item.isChecked = newStatus
    })
  }
}

// 跳转到主页
const toHome = () => {
  // 带有路径的对象
  router.push({ path: '/home' })
}

// 获取购物车的数据
const getCartList = async () => {
  // 获取购物车列表
  const res = await reqCartList()

  if (res.code === 200) {
    // 购物车为空的判断
    res.data.length ? cartList.value = res.data[0].cartInfoList : cartList.value = []

    cartList.value.forEach((item) => {
      // 旧值备份
      item.oldVal = item.skuNum
      item.isChecked = item.isChecked === 1 ? true : false
    })

  }
}

// 删除单个商品
const deleteOne = async (skuId: number | string) => {
  await reqDeleteSingle(skuId)
  getCartList()
}

// 变成输入
const changeInput = () => {
  isShowNum.value = 1
}

// 计算属性 计算全选
const allChecked = computed<boolean>({
  get() {
    return cartList.value.every((item) => (item.isChecked ? true : false))
  },
  set(newValue) {
    // newStatus.value = newValue
    newValue === true ? (newStatus.value = 1) : (newStatus.value = 0)
    // console.log(newValue)
  }
})

// 计算属性 计算总金额
const allPrice = computed(() => {
  let totalPrice = 0
  cartList.value.forEach((item) => {
    // console.log(item.isChecked)

    if (item.isChecked === true) {
      totalPrice += item.skuNum * item.skuPrice
    }
  })

  return totalPrice * 100
})

// 进入页面获取商品列表
onMounted(() => {
  getCartList()
})

</script>

<script lang="ts">
export default {
  name: 'MyCart'
}
</script>

<style lang="less" scoped>
.cart {
  background-color: #f4f4f4;
  .tip {
    font-size: 16px;
    text-align: center;
  }
  .card {
    margin: 5px 0px;
    border-radius: 25px;
    padding: 0 12px;
    display: flex;
    background-color: #ffffff;
    justify-content: space-around;
    .delete-button {
      height: 100px;
    }
    .isshownum {
      border-radius: 50%;
      border: 1px solid black;
      width: 25px;
      height: 25px;
      line-height: 25px;
      text-align: center;
    }

    .circular {
      position: fixed;
      bottom: 20px;
      right: 10px;
    }
  }
}

.outbox {
  margin-bottom: 100px;
}

.van-submit-bar {
  position: fixed;
  bottom: 50px;
}

:deep(.van-checkbox) {
  width: 60px;
}

.check {
  background-color: green;
  border-radius: 10px;
  width: 355px;
  height: 145px;
  .text {
    display: block;
  }
}
</style>
